package com.changgou.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;


@CanalEventListener //声明为canal的监听类
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * spu 表更新
     * @param eventType
     * @param rowData
     */
    @ListenPoint(schema = "changgou_goods", table = "tb_spu",eventType = CanalEntry.EventType.UPDATE )
    public void spuUp(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        System.err.println("tb_spu表数据发生变化");

        //获取改变之前的数据并将其转换成map
        Map<String,String> oldData=new HashMap<>();
        /*for(CanalEntry.Column column: rowData.getBeforeColumnsList()) {
            oldData.put(column.getName(),column.getValue());
        }*/
        rowData.getBeforeColumnsList().forEach((c)->oldData.put(c.getName(),c.getValue()));

        //获取改变之后的数据并将其转换成map
        Map newData=new HashMap<>();
        rowData.getAfterColumnsList().forEach((c)->newData.put(c.getName(),c.getValue()));

        //获取最新上架的商品 is_marketable  由0改为1表示上架
        if("0".equals(oldData.get("is_marketable")) && "1".equals(newData.get("is_marketable")) ){
            //将商品的supid发送消息到rabbitmq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",newData.get("id"));
        }

        //获取最新下架的商品
        if("1".equals(oldData.get("is_marketable")) && "0".equals(newData.get("is_marketable")) ){
            //将商品的supid发送消息到rabbitmq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",newData.get("id"));
        }
    }
}
